<?php

class PhotosController extends AdminController
{
	// ------------------------------------------------------------------------------------

	public $title = 'Фотографии';
	public $name = '/photos/';

	private $_photosDir = '';

	// ------------------------------------------------------------------------------------

	public function __construct($arg)
	{
		parent::__construct($arg);

		$this->_photosDir = Yii::app()->params['PATH_TO_PHOTOS'];
	}

	// ------------------------------------------------------------------------------------
	/**
	 * @return void
	 */
	public function actionIndex()
	{
		$data = array();
		$groups = scandir($this->_photosDir);

		for($i = 0, $iLength = count($groups); $i < $iLength; $i ++)
		{
			if($groups[$i]{0} == '.')
			{
				continue;
			}

			$group = $groups[$i];
			$groupPath = $this->_photosDir . $groups[$i];

			if(is_dir($groupPath))
			{
				$data[$group] = array();

				$files = scandir($groupPath);
				for($j = 0, $jLength = count($files); $j < $jLength; $j ++)
				{
					if(empty($files[$j]) || $files[$j]{0} == '.')
					{
						continue;
					}

					$filePath = $groupPath . '/' . $files[$j];
					if(!is_file($filePath))
					{
						continue;
					}

					$fileInfo = pathinfo($filePath);

					if(!in_array($fileInfo['extension'], array('jpg')))
					{
						continue;
					}

					$fileName = $fileInfo['filename'];

					if(substr($fileInfo['filename'], -5) == '-icon')
					{
						$fileName = str_replace('-icon', '', $fileName);
					}
					elseif(substr($fileInfo['filename'], -4) == '-src')
					{
						$fileName = str_replace('-src', '', $fileName);
					}

					if(!isset($data[$group][$fileName]))
					{
						$data[$group][$fileName] = array();
					}

					$data[$group][$fileName]['url'] = Yii::app()->params['URL_TO_PHOTOS'] . $group . '/' . $fileName . '.jpg';
					$data[$group][$fileName]['url_icon'] = Yii::app()->params['URL_TO_PHOTOS'] . $group . '/' . $fileName . '-icon.jpg';
					$data[$group][$fileName]['url_src'] = Yii::app()->params['URL_TO_PHOTOS'] . $group . '/' . $fileName . '-src.jpg';
					if(!is_file($this->_photosDir . $group . '/' . $fileName . '-icon.jpg'))
					{
						if(is_file($this->_photosDir . $group . '/' . $fileName . '-src.jpg'))
						{
							$data[$group][$fileName]['url_icon'] = $data[$group][$fileName]['url_src'];
						}
						else
						{
							$data[$group][$fileName]['url_icon'] = $data[$group][$fileName]['url'];
						}
					}
				}
			}
		}

		file_put_contents(Yii::app()->params['PATH_TO_GROUPS_FILE'], json_encode($data));

		$this->render('list', array(
			'data' => $data,
		));
	}
	
	// ------------------------------------------------------------------------------------
	/**
	 * @return void
	 */
	public function actionAdd()
	{
		$errors = array();
		$is_copied = false;
		if(!empty($_POST))
		{
			if(empty($_POST['group']))
			{
				$errors['group'] = 'Группа не может быть пустой';
			}
			
			if(empty($errors))
			{
				$groupName = $_POST['group'];
				$groupName = basename($groupName);

				if(!is_dir($this->_photosDir . $groupName))
				{
					mkdir($this->_photosDir . $groupName);
				}

				if(!empty($_POST['name']))
				{
					$fileName = $_POST['name'];
					$fileName = preg_replace('[^a-z]', '', $fileName);
				}

				if(empty($fileName))
				{
					$i = 0;
					do
					{
						$i ++;
						$fileName = str_pad($i, 2, '0', STR_PAD_LEFT);
						$filePath = $this->_photosDir . $groupName . '/' . $fileName . '.jpg';
						$filePathSource = $this->_photosDir . $groupName . '/' . $fileName . '-src.jpg';
						$filePathIcon = $this->_photosDir . $groupName . '/' . $fileName . '-icon.jpg';
					}
					while(is_file($filePath) || is_file($filePathIcon) || is_file($filePathSource));
				}
				else
				{
					$filePathSource = $this->_photosDir . $groupName . '/' . $fileName . '-src.jpg';
				}

				if(!empty($_FILES['file_upload']['tmp_name']))
				{
					$is_copied = move_uploaded_file($_FILES['file_upload']['tmp_name'], $filePathSource);
					@unlink($_FILES['file_upload']['tmp_name']);
				}
				elseif(!empty($_POST['file_download']))
				{
					$is_copied = copy($_POST['file_download'], $filePathSource);
				}

				if($is_copied)
				{
					$this->_cutIcon($filePathSource, $filePathIcon);
					$this->_cutImage($filePathSource, $filePath);
					
					$this->redirect($this->name . 'edit/' . $groupName . '/' . $fileName);
				}
			}
		}

		$groupDirs = scandir($this->_photosDir);
		$groups = array();
		for($i = 0, $iLength = count($groupDirs); $i < $iLength; $i ++)
		{
			if($groupDirs[$i]{0} == '.')
			{
				continue;
			}
			$groups[] = $groupDirs[$i];
		}

		$this->render('add', array(
			'errors' => $errors,
			'groups' => $groups,
			//'data' => $data
		));
	}
	
	// ------------------------------------------------------------------------------------
	
	protected function _cutIcon($src, $dst, $params = array())
	{
		$width = 150;
		$height = 113;

		$image = new Image($src);
		if(!empty($params))
		{
			$params['w'] = !empty($params['w']) ? intval($params['w']) : 0;
			$params['h'] = !empty($params['h']) ? intval($params['h']) : 0;
			$params['y'] = !empty($params['y']) ? intval($params['y']) : 0;
			$params['x'] = !empty($params['x']) ? intval($params['x']) : 0;
			
			$image->crop($params['w'], $params['h'], $params['y'], $params['x']);
		}
		$image->resize($width, $height, Image::NONE)->save($dst);
	}
	
	// ------------------------------------------------------------------------------------
	
	protected function _cutImage($src, $dst, $params = array())
	{
		$width = 800;
		$height = 600;

		$image = new Image($src);
		if(!empty($params))
		{
			$params['w'] = !empty($params['w']) ? intval($params['w']) : 0;
			$params['h'] = !empty($params['h']) ? intval($params['h']) : 0;
			$params['y'] = !empty($params['y']) ? intval($params['y']) : 0;
			$params['x'] = !empty($params['x']) ? intval($params['x']) : 0;
			
			$width = min($width, $_POST['w']);
			$height = min($height, $_POST['h']);
			
			$image->crop($params['w'], $params['h'], $params['y'], $params['x']);
		}
		$image->resize($width, $height);

		$image->save($dst);
	}
	
	// ------------------------------------------------------------------------------------
	/**
	 * @param bool $is_new
	 * @return void
	 */
	public function actionEdit($groupName = NULL, $fileId = NULL, $mode = NULL)
	{
		$groupName = basename($groupName);
		
		$fileName = basename($fileId) . '.jpg';
		$fileNameSource = basename($fileId) . '-src.jpg';
		$fileNameIcon = basename($fileId) . '-icon.jpg';
		
		$filePath = $this->_photosDir . $groupName . '/' . $fileName;
		$filePathSource = $this->_photosDir . $groupName . '/' . $fileNameSource;
		$filePathIcon = $this->_photosDir . $groupName . '/' . $fileNameIcon;

		if(!is_file($filePathSource))
		{
			$this->redirect($this->name, true);
			return false;
		}

		if(!empty($_FILES['icon_upload']['tmp_name']))
		{
			move_uploaded_file($_FILES['icon_upload']['tmp_name'], $filePathIcon);
			@unlink($_FILES['icon_upload']['tmp_name']);
		}
		
		if(!empty($_FILES['image_upload']['tmp_name']))
		{
			move_uploaded_file($_FILES['image_upload']['tmp_name'], $filePath);
			@unlink($_FILES['image_upload']['tmp_name']);
		}
		
		$data = array(
			//'date' => filemtime($filePath),
			'fileId' => $fileId,
			'url' => is_file($filePath) ? Yii::app()->params['URL_TO_PHOTOS'] . $groupName . '/' . $fileName : '',
			'source' => Yii::app()->params['URL_TO_PHOTOS'] . $groupName . '/' . $fileNameSource,
			'sourceIcon' => Yii::app()->params['URL_TO_PHOTOS'] . $groupName . '/' . $fileNameSource,
			'icon' => is_file($filePathIcon) ? Yii::app()->params['URL_TO_PHOTOS'] . $groupName . '/' . $fileNameIcon : '',
			'group' => $groupName
		);
		
		switch($mode)
		{
			case 'cut-icon':
				if(!empty($_POST))
				{
					$src = Yii::app()->params['PATH_TO_PHOTOS'] . $groupName . '/' . $fileNameSource;
					$dst = Yii::app()->params['PATH_TO_PHOTOS'] . $groupName . '/' . $fileNameIcon;

					$this->_cutIcon($src, $dst, $_POST);
					$this->redirect($this->name . 'edit/' . $groupName . '/' . $fileId);
				}

				$this->render('cut', array(
					'data' => $data,
					'mode' => 'icon'
				));
			break;
			
			case 'cut-image':
				if(!empty($_POST))
				{
					$src = Yii::app()->params['PATH_TO_PHOTOS'] . $groupName . '/' . $fileNameSource;
					$dst = Yii::app()->params['PATH_TO_PHOTOS'] . $groupName . '/' . $fileName;

					$this->_cutImage($src, $dst, $_POST);
					
//					$image = new Image($src);
//					$image->crop($_POST['w'], $_POST['h'], $_POST['y'], $_POST['x'])->resize($width, $height)->save($dst);
					$this->redirect($this->name . 'edit/' . $groupName . '/' . $fileId);
				}

				$this->render('cut', array(
					'data' => $data,
					'mode' => 'image'
				));
			break;
			
			default:
				$this->render('edit', array(
					'data' => $data
				));
			break;
		}
	}

	// ------------------------------------------------------------------------------------
	/**
	 * @param null $groupName
	 * @param null $fileId
	 * @return void
	 */
	public function actionDelete($groupName = NULL, $fileId = NULL)
	{
		$groupName = basename($groupName);

		$fileName = basename($fileId) . '.jpg';
		$fileNameSource = basename($fileId) . '-src.jpg';
		$fileNameIcon = basename($fileId) . '-icon.jpg';

		$filePath = $this->_photosDir . $groupName . '/' . $fileName;
		$filePathSource = $this->_photosDir . $groupName . '/' . $fileNameSource;
		$filePathIcon = $this->_photosDir . $groupName . '/' . $fileNameIcon;

		if(is_file($filePathSource))
		{
			unlink($filePathSource);
		}

		if(is_file($filePath))
		{
			unlink($filePath);
		}

		if(is_file($filePathIcon))
		{
			unlink($filePathIcon);
		}

		@rmdir($this->_photosDir . $groupName);

		$this->redirect($this->name, true);
	}

	// ------------------------------------------------------------------------------------
}
